from rest_framework.decorators import action
from rest_framework.views import Response, status
from rest_framework import viewsets, mixins
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.permissions import IsAuthenticated

from utils.common import Pagination
from .models import Faculty, FacultyDbView
from .serializers import FacultySerializer

from .utils import get_second_faculty_by_perms


class FacultyViewSet(mixins.ListModelMixin,
                     viewsets.GenericViewSet):
    queryset = Faculty.objects.all()
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    permission_classes = [IsAuthenticated]
    serializer_class = FacultySerializer
    pagination_class = Pagination
    ordering_fields = ('id', )

    @action(methods=['post'], detail=False, url_path='update_faculty')
    def update_faculty_from_dgut_db(self, request, pk=None):
        """ 从数据中心同步部门数据 """
        faculty_qs = FacultyDbView.objects.all().values()
        data_dict = {i['faculty_code']: i for i in faculty_qs}
        for code, faculty_data in data_dict.items():
            obj, created = Faculty.objects.update_or_create(faculty_code=code, defaults=faculty_data)

        Faculty.objects.exclude(faculty_code__in=data_dict.keys()).delete()
        return Response({'message': '同步完成！'})

    @action(methods=['get'], detail=False, url_path='second_faculty')
    def get_second_faculty(self, request, pk=None):
        """ 获取用户有权限查看的二级单位 """

        # 获取所有二级单位
        first_faculty_codes = Faculty.objects.filter(parent_code__isnull=True)\
            .values_list('faculty_code', flat=True)
        second_faculty_data = Faculty.objects\
            .filter(parent_code__in=first_faculty_codes)\
            .values('faculty_code', 'faculty_title')

        # 判断是否需要根据用户权限返回用户能看的
        not_by_perms = request.query_params.get('not_by_perms', None)
        add_both = request.query_params.get('add_both', True)   # 用于判断是否返回全部学院这个字段(如果可以查看全部的话)
        add_both = True if add_both is True else False
        if not_by_perms:
            res_data = second_faculty_data
        else:
            res_data = get_second_faculty_by_perms(request.user, second_faculty_data, add_both=add_both)

        return Response({'data': res_data})



